import Vue from 'vue';
import iView from 'iview';
import Axios from 'axios';
import {router} from './router/index';
import store from './store';
import App from './app.vue';
import '@/locale';
import 'iview/dist/styles/iview.css';
import VueI18n from 'vue-i18n';
import API from './api/api';
import Util from './libs/util';
import hasPermission from './libs/hasPermission.js';
import VueMoment from 'vue-moment';
import moment from 'moment';
import Cookies from 'js-cookie';

Vue.use(VueI18n);
Vue.use(iView);
Vue.use(VueMoment, {moment});
Vue.use(hasPermission);

Axios.defaults.validateStatus = status => {
    return status < 500;
}

var noNeedTokenUrl = [API.VERIFICATION_API];
// 请求拦截，请求头增加Authorization
Axios.interceptors.request.use(config => {
    let isNeedToken = true;
    for (let i = 0; i < noNeedTokenUrl.length; i++) {
        if (config.url.indexOf(noNeedTokenUrl[i]) > -1) {
            isNeedToken = false;
            break;
        }
    }
    if (isNeedToken) {
        // let routeName = app && app.$route.name;
        let token = Cookies.get('token');
        // let refreshToken = sessionStorage.getItem('refresh_token');
        // if (!token && refreshToken && routeName !== 'login') {
        //     let res = app && app.$store.dispatch('refreshToken');
        //     console.log(res);
        // }
        config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
});

// 响应拦截
Axios.interceptors.response.use(res => {
    if (res.status < 300) {
        return res.data;
    } else {
        let lock = sessionStorage.getItem('locking');
        if (lock !== '1') {
            if (res.data.error === 'E10001') {
                app && app.$Message.error(app.$t('userPasswordError'));
            } else if (res.data.error === 'E10002') {
                app && app.$Message.error(app.$t('phoneError'));
            } else if (res.data.error === 'E10003') {
                app && app.$Message.error(app.$t('verifyCodeError'));
            } else if (res.data.error === 'E10004') {
                app && app.$Message.error(app.$t('smsCodeError'));
            } else if (res.data.error === 'E10005') {
                app && app.$Message.error(app.$t('freezeOrDeleteError'));
            } else if (res.data.error === 'E40001') {
                app && app.$Message.error(app.$t('permissionError'));
            } else if (res.data.error === 'E40002') {
                app && app.$Message.error(app.$t('authError'));
            } else {
                if (res.data.error === 'invalid_token') {
                    // 刷新token并继续之前的请求
                    return app.$store.dispatch('refreshToken').then(success => {
                        if (success.access_token) {
                            res.config.__isRetryRequest = true;
                            res.config.headers.Authorization = 'Bearer ' + success.access_token;
                            return Axios(res.config);
                        }
                    }).catch(function () {
                        throw res;
                    });
                } else {
                    app && app.$Message.error(app.$t('unknowError'));
                    Cookies.remove('token');
                    sessionStorage.removeItem('user');
                    sessionStorage.removeItem('refresh_token');
                    app.$router.push({
                        name: 'login'
                    });
                }
            }
        }
    }
    return Promise.reject(new Error(app.$t('loginFailed')));
}, err => {
    app && app.$Message.error(app.$t('systemError'));
    return Promise.reject(err);
});

Vue.prototype.$http = Axios;
Vue.http = Axios;
Vue.prototype.getCookie = function (cookieName) {
    if (document.cookie.length > 0) {
        var start = document.cookie.indexOf(cookieName + '=');
        if (start !== -1) {
            start = start + cookieName.length + 1;
            var end = document.cookie.indexOf(';', start);
            if (end === -1) {
                end = document.cookie.length;
            }
            return unescape(document.cookie.substring(start, end));
        }
    }
    return '';
};
let app = new Vue({
    el: '#app',
    router: router,
    store: store,
    render: h => h(App),
    data: {
        currentPageName: ''
    },
    mounted() {
        this.currentPageName = this.$route.name;
        // 显示打开的页面的列表
        Util.initRouter(this);
        this.$store.commit('setOpenedList');
        this.$store.commit('initCachepage');
    }
});
window.app = app;
